<template>
    <div style="margin-left: 30px; margin-top: 20px; margin-right: 20px">
        <div v-if="isFormVisible">
            <!-- 表单部分 -->
        <el-form :inline="true" :model="pageParams" class="demo-form-inline">
            <el-form-item label="客户姓名">
                <el-input v-model="pageParams.name" placeholder="请输入客户姓名" clearable />
            </el-form-item>
            <el-form-item label="客户手机">
                <el-input v-model="pageParams.phone" placeholder="请输入客户手机" clearable />
            </el-form-item>
            <el-form-item label="归属人">
                <el-input v-model="pageParams.owner" placeholder="请输入线索归属人" clearable />
            </el-form-item>
            <el-form-item label="渠道来源">
                <el-select
                    v-model="pageParams.channelId"
                    placeholder="渠道来源"
                    clearable
                    @change="handleChannelChange"
                >
                    <el-option
                        v-for="channel in channelList"
                        :key="channel.channelId"
                        :label="channel.channelName"
                        :value="channel.channelId"
                    />
                </el-select>
            </el-form-item>
            <el-form-item label="线索状态">
                <el-select v-model="pageParams.status" placeholder="线索状态" clearable>
                    <el-option label="未知" value="0" />
                    <el-option label="已分配" value="1" />
                    <el-option label="跟进中" value="2" />
                    <el-option label="回收" value="3" />
                    <el-option label="伪线索" value="4" />
                </el-select>
            </el-form-item>
        </el-form>
        <el-form :inline="true" :model="pageParams" class="demo-form-inline">
            <div class="block">
                <span style="font-size: 14px"><strong>跟进时间</strong></span>
                <el-date-picker
                    v-model="pageParams.followUpDate"
                    type="daterange"
                    range-separator="-"
                    start-placeholder="开始日期"
                    end-placeholder="结束日期"
                    prefix-icon="clock"
                    style="margin-left: 10px"
                >
                </el-date-picker>
                <el-button type="primary" style="margin-bottom: 5px; margin-left: 15px" @click="search">
                    <el-icon style="margin-right: 5px"><Search /></el-icon>搜索
                </el-button>
                <el-button style="margin-bottom: 5px" @click="resetSearchForm">
                    <el-icon style="margin-right: 5px"><Refresh /></el-icon>重置
                </el-button>
            </div>
        </el-form>
        </div>
        
        <div class="flex justify-between items-center mt-4 mb-2">
            <div class="flex space-x-2">
                <el-button type="primary" plain @click="show">
                    <el-icon style="margin-right: 5px"><Plus /></el-icon>新增
                </el-button>
                <el-button type="success" plain :disabled="!canEdit" @click="edit">
                    <el-icon style="margin-right: 5px"><Edit /></el-icon>修改
                </el-button>
                <el-button type="danger" plain :disabled="!canDelete" @click="confirmDelete">
                    <el-icon style="margin-right: 5px"><DeleteFilled /></el-icon>删除
                </el-button>
            </div>
            
            <div class="flex space-x-2">
            <el-tooltip :content="isFormVisible ? '隐藏搜索' : '显示搜索'" placement="top">
                    <el-button :icon="Search" circle @click="toggleFormVisibility" />
            </el-tooltip>
            <el-button :icon="Refresh" circle @click="resetSearchForm" />
        </div>
        </div>
        <el-table
            ref="multipleTableRef"
            :data="tableData"
            row-key="id"
            style="width: 100%"
            align="center"
            @selection-change="handleSelectionChange"
        >
            <el-table-column type="selection" :selectable="selectable" />
            <el-table-column label="线索编号" align="center">
                <template #default="scope">{{ scope.row.clueId }}</template>
            </el-table-column>
            <el-table-column property="name" label="客户姓名" align="center" />
            <el-table-column property="phone" label="手机号码" align="center" />
            <el-table-column property="channelName" label="渠道来源" align="center"></el-table-column>
            <el-table-column label="创建时间" align="center">
                <template #default="scope">{{ formatDateTime(scope.row.createTime) }}</template>
            </el-table-column>
            <el-table-column property="owner" label="线索归属" align="center"></el-table-column>
            <el-table-column property="status" label="线索状态" align="center">
                <template #default="scope">
                    <el-tag v-if="scope.row.status === 0" type="danger">未知</el-tag>
                    <el-tag v-if="scope.row.status === 1" type="primary">已分配</el-tag>
                    <el-tag v-if="scope.row.status === 2" type="success">跟进中</el-tag>
                    <el-tag v-if="scope.row.status === 3" type="info">回收</el-tag>
                    <el-tag v-if="scope.row.status === 4" type="warning">伪线索</el-tag>
                </template>
            </el-table-column>
            <el-table-column label="下次跟进时间" align="center">
                <template #default="scope">{{ formatDateTime(scope.row.nextTime) }}</template>
            </el-table-column>
            <el-table-column label="操作" align="center">
                <template #default="scope">
                    <div class="flex items-center justify-center">
                        <!-- 所有状态都显示查看按钮 -->
                        <p @click="viewDetail(scope.row)" class="text-blue mr-4">
                            <el-icon style="display: inline-block; margin-top: 0px !important"><View /></el-icon>查看
                        </p>
                        
                        <!-- 归属人为admin01时显示分配和跟进按钮 -->
                        <p v-if="scope.row.owner === 'admin01' && scope.row.status === 1" @click="assign(scope.row)" class="text-blue mr-4">
                            <el-icon style="display: inline-block; margin-top: 0px !important"><Pointer /></el-icon>分配
                        </p>
                        <p v-if="scope.row.owner === 'admin01' && scope.row.status === 1" @click="viewFlow(scope.row)" class="text-blue">
                            <el-icon style="display: inline-block; margin-top: 0px !important"><TopRight /></el-icon>跟进
                        </p>
                        
                        <!-- 归属人不是admin01，但状态是已分配时显示分配按钮 -->
                        <p v-else-if="scope.row.owner !== 'admin01' && scope.row.status === 1" @click="assign(scope.row)" class="text-blue mr-4">
                            <el-icon style="display: inline-block; margin-top: 0px !important"><Pointer /></el-icon>分配
                        </p>
                        
                        <!-- 归属人不是admin01，但状态是跟进中时显示跟进按钮 -->
                        <p v-else-if=" scope.row.status === 2" @click="viewFlow(scope.row)" class="text-blue">
                            <el-icon style="display: inline-block; margin-top: 0px !important"><TopRight /></el-icon>跟进
                        </p>
                    </div>
                </template>
            </el-table-column>
        </el-table>

        <div class="pagination-container">
            <el-pagination
                v-model:current-page="pageParams.pageNum"
                v-model:page-size="pageParams.pageSize"
                :page-sizes="[10, 20, 30, 40]"
                 :size="size"
                :disabled="disabled"
                background
                layout="total, sizes, prev, pager, next, jumper"
                :total="total"
                @size-change="handleSizeChange"
                @current-change="handleCurrentChange"
                style="margin-top: 20px"
            />
        </div>

        <!-- 线索对话框 -->
        <el-dialog v-model="dialogVisible" :title="title" width="700px" center>
            <el-form ref="addFormRef" :model="addForm" :rules="addRules" label-width="100px">
                <el-row :gutter="20">
                    <el-col :span="12">
                        <el-form-item label="手机号码" prop="phone">
                            <el-input v-model="addForm.phone" placeholder="请输入手机号码" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="客户姓名" prop="name">
                            <el-input v-model="addForm.name" placeholder="请输入客户姓名" />
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row :gutter="20">
                    <el-col :span="12">
                        <el-form-item label="渠道来源" prop="channelId">
                            <el-select
                                v-model="addForm.channelId"
                                placeholder="渠道来源"
                                clearable
                                @change="handleChannelChange"
                            >
                                <el-option
                                    v-for="channel in channelList"
                                    :key="channel.channelId"
                                    :label="channel.channelName"
                                    :value="channel.channelId"
                                />
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="活动信息" prop="activityId">
                            <el-select v-model="addForm.activityId" placeholder="请选择活动信息" clearable>
                                <el-option
                                    v-for="activity in activityList"
                                    :key="activity.activityId"
                                    :label="activity.name"
                                    :value="activity.activityId"
                                />
                            </el-select>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row :gutter="20">
                    <el-col :span="12">
                        <el-form-item label="客户性别" prop="gender">
                            <el-radio-group v-model="addForm.gender">
                                <el-radio :label="1">男</el-radio>
                                <el-radio :label="0">女</el-radio>
                                <el-radio :label="2">未知</el-radio>
                            </el-radio-group>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="客户年龄" prop="age">
                            <el-input-number v-model="addForm.age" placeholder="年龄" />
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row :gutter="20">
                    <el-col :span="12">
                        <el-form-item label="微信号" prop="weixin">
                            <el-input v-model="addForm.weixin" placeholder="请输入微信号码" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="QQ号码" prop="qq">
                            <el-input v-model="addForm.qq" placeholder="请输入QQ号码" />
                        </el-form-item>
                    </el-col>
                </el-row>
            </el-form>
            <template #footer>
                <span class="dialog-footer" style="display: flex; justify-content: flex-end">
                    <el-button type="primary" @click="submitForm(addFormRef)">确定</el-button>
                    <el-button @click="resetForm(addFormRef)">取消</el-button>
                </span>
            </template>
        </el-dialog>
        <el-dialog v-model="changeVisible" style="width: 700px; height: 230px;" title="分配线索">
            <el-form ref="assignFormRef" :model="assignForm" :rules="assignRules" label-width="100px">
                <el-row :gutter="20">
                    <el-col :span="12">
                        <el-form-item label="归属部门" prop="channelId">
                            <el-tree-select
                                v-model="assignForm.channelId"
                                :data="deptList"
                                :props="{ label: 'label', value: 'id' }"
                                placeholder="请选择归属部门"
                                clearable
                                @change="handleDeptChange"
                                check-strictly
                            />
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="分配给" prop="activityId">
                            <el-select v-model="assignForm.activityId" placeholder="选择用户" clearable>
                                <el-option
                                    v-for="user in userList"
                                    :key="user.userId"
                                    :label="user.nickName"
                                    :value="user.userId"
                                />
                            </el-select>
                        </el-form-item>
                    </el-col>
                </el-row>
            </el-form>
            <template #footer>
                <span class="dialog-footer" style="display: flex; justify-content: flex-end">
                    <el-button type="primary" @click="submitAssignForm">确定</el-button>
                    <el-button @click="changeVisible = false">取消</el-button>
                </span>
            </template>
        </el-dialog>
    </div>
</template>

<script lang="ts" setup>
import {
  Edit,
  Search,
  Refresh,
  View,
  Pointer,
  TopRight
} from '@element-plus/icons-vue'
import { reactive, ref, computed, onMounted, nextTick } from 'vue';
import { useRouter } from 'vue-router';
import type { TableInstance, ComponentSize, FormInstance } from 'element-plus';
import { getClue, getChange, deleteId, addClue, getActivity, updateClue, getSummary, getTreeselect, getUsers, addAssignment } from '@/api/clue/clue';
import { ElMessage, ElMessageBox } from 'element-plus';

const router = useRouter();

const multipleTableRef = ref<TableInstance>();
const multipleSelection = ref([]);
const dialogVisible = ref(false);
const changeVisible = ref(false);
const addFormRef = ref<FormInstance>();
const title = ref('添加线索');
const id = ref('');

const userList = ref<any[]>([]); //用户列表

const selectable = (row: any) => ![1, 2].includes(row.id);
const handleSelectionChange = (val: any[]) => {
    multipleSelection.value = val;
};

// 计算属性：是否可以编辑（选中且仅选中一项）
const canEdit = computed(() => {
    return multipleSelection.value.length === 1;
});

// 计算属性：是否可以删除（至少选中一项）
const canDelete = computed(() => {
    return multipleSelection.value.length > 0;
});

const tableData = ref<any[]>([]);
const channelList = ref<any[]>([]);

const isFormVisible = ref(true);
const size = ref<ComponentSize>('default');
const disabled = ref(false);
const pageParams = reactive({
    pageNum: 1, // 页码
    pageSize: 10, // 每页条数
    name: '', // 客户姓名
    phone: '', // 客户手机
    owner: '', // 归属人
    channelId: '', // 渠道来源
    status: '', // 线索状态
    followUpDate: [], // 跟进时间范围
});

let total = ref(0);

// 活动信息列表
const activityList = ref<any[]>([]);

const addForm = reactive({
    phone: '',
    name: '',
    channelId: '',
    activityId: '',
    gender: 1,
    age: '',
    weixin: '',
    qq: '',
});

// 分配线索表单引用
const assignFormRef = ref<FormInstance>();

// 分配线索表单数据
const assignForm = reactive({
    assignId: '',
    channelId: '', // 归属部门
    activityId: '' // 分配给
});

// 分配线索表单验证规则
const assignRules = {
    channelId: [
        { required: true, message: '归属部门不能为空', trigger: 'change' }
    ],
    activityId: [
        { required: true, message: '分配给不能为空', trigger: 'change' }
    ]
};

// 归属部门列表
const deptList = ref<any[]>([]);

// 表单验证
const addRules = {
    phone: [{ required: true, message: '手机号码不能为空', trigger: 'blur' }],
    name: [{ required: true, message: '客户姓名不能为空', trigger: 'blur' }],
};
const departmentId = ref(null);

onMounted(() => {
    getList();
    getChannelList();
    getDeptList();
});
// 切换表单显示状态的方法
const toggleFormVisibility = () => {
    isFormVisible.value = !isFormVisible.value;
};
function removeEmojis(str) {
    return str.replace(/[\u{1F600}-\u{1F64F}\u{1F300}-\u{1F5FF}\u{1F680}-\u{1F6FF}\u{1F1E0}-\u{1F1FF}\u{2600}-\u{26FF}\u{2700}-\u{27BF}]/gu, '');
}

// 修改提交分配表单的方法
const submitAssignForm = async () => {
    if (!assignFormRef.value) return;
    await assignFormRef.value.validate((valid, fields) => {
        if (valid) {
            const user = userList.value.find(user => user.userId === assignForm.activityId);
            if (!user) {
                ElMessage.error('未找到用户信息');
                return;
            }

            const nickName = user.nickName || '';
            const userName = user.userName || '';

            if (!userName) {
                ElMessage.error('用户名为空，请选择其他用户');
                return;
            }

            if (!departmentId.value) {
                ElMessage.error('请先选择归属部门');
                return;
            }

            const assignmentData = {
                assignId: Number(assignForm.assignId), 
                deptId: Number(assignForm.channelId),
                userId: Number(assignForm.activityId),
                userName: userName,
                nickName: nickName,
                departmentId: departmentId.value, 
                type: 0, 
                remark: '', 
                latest: false 
            };

            console.log('分配线索请求参数:', assignmentData);

            addAssignment(assignmentData)
               .then(res => {
                    console.log('分配线索响应数据:', res);
                    if (res.code === 200 || res.code === 201) {
                        ElMessage.success('分配成功');
                        changeVisible.value = false;
                        getList(); // 重新加载列表
                    } else {
                        ElMessage.error('分配失败: ' + (res.message || '未知错误'));
                    }
                })
               .catch(error => {
                    ElMessage.error('分配失败');
                    console.error('分配失败:', error);
                });
        } else {
            console.log('error submit!', fields);
        }
    });
};

function getList() {
    console.log('查询参数:', pageParams);
    getClue(pageParams)
        .then(res => {
            console.log('查询结果:', res);
            tableData.value = res.rows || [];
            total.value = res.total || 0;
        })
        .catch(error => {
            console.error('获取列表失败:', error);
        });
}

function getChannelList() {
    getChange({})
        .then(res => {
            if (res.code === 200) {
                channelList.value = res.data || [];
            } else {
                console.error('获取渠道列表失败:', res.message);
            }
        })
        .catch(error => {
            console.error('获取渠道列表错误:', error);
        });
}

function getDeptList() {
    getTreeselect({})
        .then(res => {
            if (res.code === 200) {
                deptList.value = res.data;
            } else {
                console.error('获取归属部门列表失败:', res.message);
            }
        })
        .catch(error => {
            console.error('获取归属部门列表错误:', error);
        });
}

const handleSizeChange = (val: number) => {
    pageParams.pageNum = 1;
    pageParams.pageSize = val;
    getList();
};

const handleCurrentChange = (val: number) => {
    pageParams.pageNum = val;
    getList();
};

function search() {
    // 重置页码为第一页
    pageParams.pageNum = 1;
    getList();
}

function resetForm(formEl: FormInstance | undefined) {
    if (!formEl) return;
    formEl.resetFields();
    dialogVisible.value = false;
}

// 添加专门用于重置搜索表单的方法
function resetSearchForm() {
    pageParams.name = '';
    pageParams.phone = '';
    pageParams.owner = '';
    pageParams.channelId = '';
    pageParams.status = '';
    pageParams.followUpDate = [];
    pageParams.pageNum = 1; // 重置页码为第一页
    getList(); // 重新加载列表
}

// 分配按钮点击事件
function assign(row) {
    changeVisible.value = true;
    // 清空之前的选择
    assignForm.channelId = '';
    assignForm.activityId = '';
    userList.value = [];
    assignForm.assignId = row.clueId; 
}

// 格式化日期时间，去掉 T
const formatDateTime = (dateTime: string) => {
    if (!dateTime) return '';
    return dateTime.replace('T', ' ');
};

// 确认删除
function confirmDelete() {
    const clueIds = multipleSelection.value.map(item => item.clueId).join(',');
    if (clueIds) {
        ElMessageBox.confirm(`是否确认删除线索编号为 "${clueIds}" 的数据项？`, '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning',
        })
           .then(() => {
                deleteId(clueIds)
                   .then(res => {
                        ElMessage.success('删除成功');
                        getList();
                    })
                   .catch(error => {
                        ElMessage.error('删除失败');
                        console.error('删除失败:', error);
                    });
            })
           .catch(() => {
                ElMessage.info('已取消删除');
            });
    }
}
// 编辑
async function edit() {
    if (multipleSelection.value.length === 1) {
        const row = multipleSelection.value[0];
        console.log('选中行的数据:', row);
        dialogVisible.value = true;
        title.value = '修改线索';
        id.value = row.clueId;

        try {

            const res = await getSummary(row.clueId);
            const data = res.data;

            addForm.phone = data.phone || '';
            addForm.name = data.name || '';
            addForm.channelId = data.channelId || '';
            addForm.activityId = data.activityId || '';
            addForm.gender = data.gender || 1;
            addForm.age = data.age || '';
            addForm.weixin = data.weixin || '';
            addForm.qq = data.qq || '';

            // 获取活动信息列表
            getActivityListData(data.channelId);
        } catch (error) {
            console.error('获取线索详细信息失败:', error);
            ElMessage.error('获取线索详细信息失败');
        }
    }
}

const submitForm = async (formEl: FormInstance | undefined) => {
    if (!formEl) return;
    await formEl.validate((valid, fields) => {
        if (valid) {
            if (title.value === '添加线索') {
                // 新增接口
                addClue(addForm)
                   .then(res => {
                        ElMessage({
                            message: '新增成功',
                            type: 'success',
                        });
                        dialogVisible.value = false;
                        getList();
                    })
                   .catch(error => {
                        ElMessage.error('新增失败');
                        console.error('新增失败:', error);
                    });
            } else {
                // 修改
                const updateData = {
                    clueId: id.value, 
                    ...addForm,
                };
                updateClue(updateData)
                   .then(res => {
                        ElMessage.success('修改成功');
                        dialogVisible.value = false;
                        getList();
                    })
                   .catch(error => {
                        ElMessage.error('修改失败');
                        console.error('修改失败:', error);
                    });
            }
        } else {
            console.log('error submit!', fields);
        }
    });
};

// 打开弹框
function show() {
    dialogVisible.value = true;
    title.value = '添加线索';
    // 重置表单
    nextTick(() => {
        if (addFormRef.value) {
            addFormRef.value.resetFields();
        }
        addForm.phone = '';
        addForm.name = '';
        addForm.channelId = '';
        addForm.activityId = '';
        addForm.gender = 1;
        addForm.age = '';
        addForm.weixin = '';
        addForm.qq = '';
        activityList.value = [];
    });
}

function handleChannelChange(channelId: number) {
    getActivityListData(channelId);
}

// 获取活动信息列表
function getActivityListData(channelId: number) {
    if (channelId) {
        getActivity(channelId)
           .then(res => {
                if (res.code === 200) {
                    activityList.value = res.data || [];
                    console.log('活动信息列表:', activityList.value);
                } else {
                    ElMessage.error(res.message || '获取活动信息失败');
                }
            })
           .catch(error => {
                console.error('获取活动信息错误:', error);
                ElMessage.error('获取活动信息失败');
            });
    } else {
        // 如果没有选择渠道，清空活动列表
        activityList.value = [];
    }
}

// 查看详情
function viewDetail(row) {
    router.push({ name: 'ClueDetail', params: { clueId: row.clueId } });
}

function viewFlow(row) {
    router.push({ name: 'ClueFlow', params: { clueId: row.clueId } });
}

const handleDeptChange = (deptId: number) => {
    if (deptId) {
        // 存储选中的部门ID
        departmentId.value = deptId;
        
        getUsers(deptId)
           .then(res => {
                if (res.code === 200) {
                    userList.value = res.data || [];
                    console.log('用户列表:', userList.value);
                } else {
                    ElMessage.error(res.message || '获取用户列表失败');
                }
            })
           .catch(error => {
                console.error('获取用户列表错误:', error);
                ElMessage.error('获取用户列表失败');
            });
    } else {
        // 如果没有选择部门，清空用户列表和部门ID
        userList.value = [];
        departmentId.value = null;
    }
};
</script>

<style scoped>
.demo-form-inline .el-input {
    --el-input-width: 220px;
}

.demo-form-inline .el-select {
    --el-select-width: 220px;
}


.pagination-container {
    display: flex;
    justify-content: flex-end;
    margin-top: 30px;
}
.text-blue {
    color: var(--el-color-primary);
    cursor: pointer; 
}
.text-blue .el-icon {
    margin-right: 6px;
}
.text-blue .el-icon svg {
    height: 1em;
    width: 1em;
    margin-top: -3px;
}
</style>    